package com.gzsxy.sso.core.controller;


import com.gzsxy.sso.common.dto.request.PermissionRequest;
import com.gzsxy.sso.common.dto.response.MenuRsp;
import com.gzsxy.sso.common.result.R;
import com.gzsxy.sso.core.entity.Permission;
import com.gzsxy.sso.core.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *  权限管理
 * @author zxl
 * @since 2021-11-10
 */
@Api(description = "权限管理")
@CrossOrigin  //解决跨域
@RestController
@RequestMapping("/admin/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @ApiOperation("查询所有权限")
    @GetMapping("/getAll")
    public R getAllPermission(){
        List<Permission> permission = permissionService.findAllPermission();
        return R.ok().message("查询成功").data("permission",permission);
    }


    @ResponseBody
    @GetMapping("/order1")
    public String test3(){
        String username = null;
        //当前认证通过的用户身份 (获取当前上下文)
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //用户身份
        Object principal = authentication.getPrincipal();
        if (principal == null){
            username = "匿名";
        }
        if (principal instanceof org.springframework.security.core.userdetails.UserDetailsService){
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();
        }
        return "我是order";
    }



    @ApiOperation("根据角色添加权限")
    @PostMapping("/role/{roleId}")
    public R addpermissionByRole(
            @ApiParam(value = "角色id",required = true) @PathVariable String roleId,
            @RequestBody PermissionRequest permissionRequest
            ){
        permissionService.addPermissionByRole(roleId,permissionRequest.getMenuIds());
        return R.ok().message("添加成功");
    }


    @ApiOperation("删除角色下的功能权限")
    @DeleteMapping("/{roleId}/funcation/{menuId}")
    public R deletefunctionByRoles(@ApiParam(value = "角色id",required = true) @PathVariable String roleId,
                                   @ApiParam(value = "菜单id",required = true) @PathVariable String menuId){
        List<MenuRsp> list = permissionService.deletefunctionByRoles(roleId, menuId);
        return R.ok().message("删除成功").data("data",list);
    }



}

